layui.define('view', function(exports){
    var $ = layui.jquery;
    var layer = layui.layer;
    var setter = layui.setter;
    var admin = layui.admin;
    var server = {
        //  ajax请求
        req:function(options){
            if(typeof options != 'object'){
                return layer.msg('options error');
            }
            var checkToken = true;
            if(options.unsetCheckToken){
                checkToken = false;
            }
            options.data = options.data || {};
            if (admin.getUserInfo().hasOwnProperty('userId') && admin.getUserInfo().hasOwnProperty('token')) {
                options.data.userId = admin.getUserInfo().userId;
                options.data.token = admin.getUserInfo().token;
            }
            $.ajax({
                url: setter.base_server + options.url,
                async:!options.async,
                data: options.data || {},
                type: options.method || 'get',
                timeout:options.timeout || 5000,
                dataType: 'JSON',
                success: function (data) {
                    layer.closeAll('loading');
                    if(data.errorCode == 0){
                        options.callback(data);
                    }else if(data.errorCode == 901){
                        layer.msg('请登录', {icon: 2,time:1500}, function () {
                            //  跳转登录页
                            location.replace('#/user/login');
                        });
                    }else{
                        layer.msg(data.errorMessage, {icon: 2,time:1500});
                    }
                },
                error: function () {
                    layer.closeAll('loading');
                    layer.msg('请求超时,尝试刷新或重新登录!', {icon: 2});
                },
                beforeSend: function () {
                    //防止重复提交，弹出一个带遮罩的加载层，等待请求结束后恢复
                    layer.load({shade: 0.2,time:99999});
                },
            });
        },

        getToken:function(){
            return layui.data(setter.tableName).userInfo.token;
        },

        open:function(options){
            return layer.open({
                type:options.type || 1,
                title:options.title || '标题',
                area:options.area || ['400px','400px'],
                content:options.content || '',
            });
        }
    };
    

    exports('server', server);
});